package src;

import java.util.Random;


public class Lottery {
	
	public Process [] schedule = new Process[1000];
	public int timer = 0;
	public Process [] addedpro = new Process[1000];
	int finishedpro = 0;
	
	public Lottery(){
		
		this.run();
		
	}
	
	public void add(Process p){
		
		int x = 0;
		while(addedpro[x] != null){x++;}
		addedpro[x] = p;
		
		for(int i = 0;i<p.user.priority; i++){
			
			int j = 0;
			while(schedule[j] != null){j++;}
			schedule[j] = p;
			
		}
		
	}
	
	public void run(){
		
		User u1 = new User("user1",1);
		User u2 = new User("user1",2);
		User u3 = new User("user1",3);
		Process [] pro = {
				new Process("process 1", 0, 3, u1),
				new Process("process 2", 1, 4, u1),
				new Process("process 3", 5, 7, u2),
				new Process("process 4", 6, 8, u3),
				new Process("process 5", 7, 2, u2)
				};
		
		int totruntime = totalrun(pro);
		
		while(timer < totruntime){
			
			for(int i = 0;i<pro.length;i++){
				if(pro[i].arrival <= timer && !added(pro[i]))
					this.add(pro[i]);
			}

			Random r = new Random();
			int index = r.nextInt(numadded()-finishedpro);
			
			if(schedule[index].remainingtime == 0){
				
				for(int i=0; i<schedule.length && schedule[i] != null; i++)
					if(schedule[i].name == schedule[index].name)
						this.shiftleft(i);
				
				
			}
			
			if(schedule[index].remainingtime == 1 || schedule[index].remainingtime == 2){
				if(schedule[index].remainingtime == 1){
					schedule[index].remainingtime--;
					schedule[index].run(timer);
					timer++;
				}else{
					schedule[index].remainingtime--;
					schedule[index].run(timer);
					timer++;
					schedule[index].remainingtime--;
					schedule[index].run(timer);
					timer++;
				}
				System.out.println("Process " + schedule[index].name + " has finished");
				for(int i=0; i<schedule.length && schedule[i] != null; i++){
					
					if(schedule[i].name == schedule[index].name)
						this.shiftleft(i);
					
				}
				finishedpro++;
				continue;
			}
			schedule[index].remainingtime--;
			schedule[index].run(timer);
			timer++;
			schedule[index].remainingtime--;
			schedule[index].run(timer);
			timer++;
		}
		
	}
	
	public boolean added(Process p) {
		
		for(int i = 0; i<addedpro.length && addedpro[i] != null; i++)
			if(addedpro[i].name.equalsIgnoreCase(p.name))
					return(true);
		return (false);
		
	}

	public int numadded() {
		
		int totalnumberofprocesses = 0;
		for(int i = 0; i<addedpro.length; i++)
			if(addedpro[i] != null)
				totalnumberofprocesses ++;
		
		return(totalnumberofprocesses);
	}

	public int totalrun(Process[] p) {
		
		int totruntime = 0;
		for(int i = 0; i<p.length; i++)
			totruntime += p[i].runtime;
		return(totruntime);
		
	}

	public void shiftleft(int startindex){
		
		for(int i=startindex; i<schedule.length-1; i++){
			
			schedule[i]=schedule[i+1];
			
		}
		
	}

}
